<template>
  <div class="breadcrumb-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index" :to="item.path">
        {{ item.title }}
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';

// 定义组件属性
const props = defineProps({
  // 自定义面包屑项，如果提供则使用自定义项
  customItems: {
    type: Array,
    default: () => []
  },
  // 是否自动生成面包屑（根据路由）
  autoGenerate: {
    type: Boolean,
    default: true
  }
});

// 获取当前路由
const route = useRoute();

// 面包屑项
const breadcrumbItems = ref([]);

// 根据路由路径生成面包屑
const generateBreadcrumbFromRoute = () => {
  const paths = route.path.split('/').filter(Boolean);
  const items = [];
  
  // 添加首页
  items.push({
    title: '首页',
    path: '/'
  });
  
  // 根据路径构建面包屑
  let currentPath = '';
  paths.forEach(path => {
    currentPath += `/${path}`;
    
    // 获取路径对应的标题
    let title = path.charAt(0).toUpperCase() + path.slice(1);
    
    // 如果路由有meta.title，则使用它
    const matchedRoute = route.matched.find(r => r.path === currentPath);
    if (matchedRoute && matchedRoute.meta && matchedRoute.meta.title) {
      title = matchedRoute.meta.title;
    }
    
    items.push({
      title,
      path: currentPath
    });
  });
  
  return items;
};

// 更新面包屑
const updateBreadcrumb = () => {
  if (props.customItems && props.customItems.length > 0) {
    breadcrumbItems.value = props.customItems;
  } else if (props.autoGenerate) {
    breadcrumbItems.value = generateBreadcrumbFromRoute();
  } else {
    breadcrumbItems.value = [];
  }
};

// 监听路由变化
watch(() => route.path, updateBreadcrumb, { immediate: true });

// 监听自定义项变化
watch(() => props.customItems, updateBreadcrumb, { deep: true });
</script>

<style scoped>
.breadcrumb-container {
  padding: 16px 0;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  padding-left: 20px;
  border-radius: 4px;
}
</style>